import './store-browser-card.scss';
import {classnames, designPage, reactive, useRefs, watch} from "@peryl/react-compose";
import {zeroize} from '@peryl/utils/zeroize';
import {DatePicker, i18n} from 'plain-design';
import {usePageService} from "../../../modules/micro/usePageService";
import {DataStatisticHead} from '../common/data-statistic-head';
import {useEchartsColor} from "../../../components/useEchartsColor";

export default designPage(() => {

  const storeBrowserList = [
    { name: i18n.$intl('page.dataStatistic.store1').d(''), count: '4,335' },
    { name: i18n.$intl('page.dataStatistic.store2').d(''), count: '3,754' },
    { name: i18n.$intl('page.dataStatistic.store3').d(''), count: '3,346' },
    { name: i18n.$intl('page.dataStatistic.store4').d(''), count: '3,215' },
    { name: i18n.$intl('page.dataStatistic.store5').d(''), count: '3,024' },
    { name: i18n.$intl('page.dataStatistic.store6').d(''), count: '3,004' },
    { name: i18n.$intl('page.dataStatistic.store7').d(''), count: '2,856' },
  ];

  const { color1, color6 } = useEchartsColor();

  const { refs, onRef } = useRefs({ chartEl: HTMLDivElement });

  const { microApp } = usePageService();

  const state = reactive({
    filterStart: null as any,
    filterEnd: null as any,
    currentFilterType: 2,
  });

  const filters = [
    {
      label: i18n.$intl('page.dataStatistic.today').d('今日'),
      start: DatePicker.plainDate.today().getDayJs(),
      end: DatePicker.plainDate.today().getDayJs(),
      labels: new Array(24).fill(0).map((_, i) => `${zeroize(i)}:00`),
      range: [100, 300],
    },
    {
      label: i18n.$intl('page.dataStatistic.week').d('本周'),
      start: DatePicker.plainDate.today().getDayJs().startOf('week'),
      end: DatePicker.plainDate.today().getDayJs().endOf('week'),
      labels: [
        i18n.$intl('page.dataStatistic.monday').d('周一'),
        i18n.$intl('page.dataStatistic.tuesday').d('周二'),
        i18n.$intl('page.dataStatistic.wednesday').d('周三'),
        i18n.$intl('page.dataStatistic.thursday').d('周四'),
        i18n.$intl('page.dataStatistic.friday').d('周五'),
        i18n.$intl('page.dataStatistic.saturday').d('周六'),
        i18n.$intl('page.dataStatistic.sunday').d('周日'),
      ],
      range: [1000, 5000],
    },
    {
      label: i18n.$intl('page.dataStatistic.month').d('本月'),
      start: DatePicker.plainDate.today().getDayJs().startOf('month'),
      end: DatePicker.plainDate.today().getDayJs().endOf('month'),
      labels: (() => {
        let lastDateOfYear = DatePicker.plainDate.today();
        return new Array(lastDateOfYear.getDayJs().daysInMonth()).fill(0).map((_, i) => `${i + 1}${i18n.$intl('page.dataStatistic.day').d('日')}`);
      })(),
      range: [20000, 100000],
    },
    {
      label: i18n.$intl('page.dataStatistic.year').d('全年'),
      start: DatePicker.plainDate.today().getDayJs().startOf('year'),
      end: DatePicker.plainDate.today().getDayJs().endOf('year'),
      labels: [
        i18n.$intl('page.dataStatistic.january').d('一月'),
        i18n.$intl('page.dataStatistic.february').d('二月'),
        i18n.$intl('page.dataStatistic.march').d('三月'),
        i18n.$intl('page.dataStatistic.april').d('四月'),
        i18n.$intl('page.dataStatistic.may').d('五月'),
        i18n.$intl('page.dataStatistic.june').d('六月'),
        i18n.$intl('page.dataStatistic.july').d('七月'),
        i18n.$intl('page.dataStatistic.august').d('八月'),
        i18n.$intl('page.dataStatistic.september').d('九月'),
        i18n.$intl('page.dataStatistic.october').d('十月'),
        i18n.$intl('page.dataStatistic.november').d('十一月'),
        i18n.$intl('page.dataStatistic.december').d('十二月'),
      ],
      range: [100000, 1000000],
    },
  ];

  async function updateCharts(labels: string[], ranges: [number, number]) {
    const [rangeStart, rangeEnd] = ranges;
    const echarts = await microApp.resource.load('echarts', window);
    const ins = echarts.init(refs.chartEl!);

    const dataAxis = labels;
    const data = labels.map(() => Math.ceil(Math.random() * rangeEnd - rangeStart) + rangeStart);

    const option = {
      grid: {
        top: '3%',
        left: `${String(rangeEnd).length}%`,
        right: '0%',
        bottom: '7%',
      },
      xAxis: {
        type: 'category',
        data: dataAxis,
      },
      yAxis: {
        type: 'value',
        splitLine: {
          lineStyle: {
            color: 'rgba(0,0,0,0.05)',
          }
        },
      },
      series: [
        {
          type: 'bar',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(
              0, 0, 0, 1,
              [
                { offset: 0, color: color1 },
                { offset: 1, color: color6 }
              ]
            )
          },
          data: data
        }
      ]
    };
    ins.setOption(option);
  }

  async function setFilter(index: number) {
    const filter = filters[index]!;
    state.filterStart = filter.start.format('YYYY-MM-DD');
    state.filterEnd = filter.end.format('YYYY-MM-DD');
    await updateCharts(filter.labels, filter.range as any);
  }

  watch(() => state.currentFilterType, async () => {
    setFilter(state.currentFilterType);
  }, { immediate: true });

  return () => (
    <div className="store-browser-card pro-data-statistic-summary-card">
      <div className="store-browser-card-wrapper">
        <DataStatisticHead icon="pi-image" title={i18n.$intl('page.dataStatistic.visit').d("访问量")}>
          {filters.map((i, index) => <span
            onClick={() => state.currentFilterType = index}
            className={
              classnames([
                'store-browser-filter-type',
                { 'pl-text-primary': index === state.currentFilterType }
              ])
            } key={i.label}>{i.label}</span>)}
          <DatePicker range v-model:start={state.filterStart} v-model:end={state.filterEnd} popperAttrs={{ placement: 'bottom-end' }} inputAttrs={{ width: 300 }}/>
        </DataStatisticHead>
        <div className="store-browser-card-body">
          <div className="store-browser-card-chart" ref={onRef.chartEl}/>
          <div className="store-browser-card-store-list">
            <div>{i18n.$intl('page.dataStatistic.storeVisitRank').d('门店访问量排行')}</div>
            {storeBrowserList.map((item, index) => (
              <div className="store-browser-card-store-item" key={index}>
                <div>
                  <div className="store-browser-card-store-item-rank">{index + 1}</div>
                  <span>{item.name}</span>
                </div>
                <div>
                  {item.count}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
});
